<template>
  <div id="jobScheduling">
    <Breadcrumb content="工作排班" />
    <div class="bodyContent">
      <Splitpanes class="area">
        <Pane size="18">
          <div class="cu-list menu" style="height: calc(100vh - 90px); overflow-y: auto">
            <div class="cu-item" :class="idx === 0 ? '' : 'margin-top-xs'" v-for="(itm, idx) in scheTypeList" :key="idx">
              <div class="content padding-lr padding-tb-xs text-bold flex justify-start radius" :style="{ backgroundColor: itm.bgColor, color: itm.wordColor }">
                <div>{{ itm.symbol }}</div>
                <div class="margin-left-xs">{{ itm.name }}</div>
                <div class="margin-left-xs">{{ itm.remark }}</div>
              </div>
            </div>
            <div class="margin-top-xs padding-lr-xs padding-tb-xs text-olive">
              <span>&nbsp;&nbsp;&nbsp;&nbsp;各营运部门每月2日前将当月排班表按时交至人力资源部存档，作为年终考核的依据之一。</span>
            </div>
          </div>
        </Pane>
        <Pane size="82">
          <vxe-toolbar perfect>
            <template #buttons>
              <span class="margin-right-xs">月份:</span>
              <vxe-input v-model="form.date" type="month" valueFormat="yyyy-MM" @change="getColumnList" style="width: 100px"></vxe-input>
              <vxe-button type="text" status="primary" icon="vxe-icon-refresh" class="button-blue" :loading="showLoading" content="刷新" @click="getColumnList"></vxe-button>
              <vxe-button type="text" status="success" icon="vxe-icon-square-plus" class="button-blue" content="新增" @click="handleAdd('')"></vxe-button>
              <vxe-button type="text" status="danger" icon="vxe-icon-delete" class="button-red" content="删除" @click="handleDelete"></vxe-button>
              <vxe-button type="text" status="success" icon="vxe-icon-file-txt" class="button-blue" content="检验科排班" @click="expendEmployee"></vxe-button>
              <vxe-button type="text" status="success" icon="vxe-icon-square-right-fill" class="button-blue" content="下月快速排班" @click="createNextMonthScheRec"></vxe-button>
              <vxe-button type="text" status="success" icon="vxe-icon-upload" class="button-blue" content="导入" @click="importExcelData"></vxe-button>
            </template>
          </vxe-toolbar>
          <div class="jobSchedulingTable">
            <vxe-table ref="jobSchedulingTable" v-loading="loading" :border="'full'" height="auto" :data="tableDataList" :column-config="{ isCurrent: true, isHover: true }" :row-config="{ isCurrent: true, isHover: true }" :mouse-config="{ selected: true }" :keyboard-config="{ isArrow: true, isTab: true, isEdit: true }" :edit-config="{ trigger: 'click', mode: 'cell', showIcon: false, enabled: true }" resizable show-overflow>
              <vxe-column type="checkbox" width="26" align="center"></vxe-column>
              <vxe-column type="seq" title="序号" width="30"></vxe-column>
              <vxe-column field="EmployeeName" title="姓名" align="center" width="50" :edit-render="{ autofocus: '.vxe-input--inner' }">
                <template #default="{ row }">
                  <span>{{ formatterEmployee(row.employeeId) }}</span>
                </template>
                <template #edit="{ row }">
                  <vxe-select v-model="row.employeeId" placeholder="员工" clearable>
                    <vxe-option v-for="item in monthDataEmployeeMap[form.date]" :key="item.id" :value="item.id" :label="item.name"></vxe-option>
                  </vxe-select>
                </template>
              </vxe-column>
              <vxe-colgroup title="班次情况" align="center">
                <template #header>
                  <div class="text-lg padding-tb text-bold text-black">班次情况</div>
                </template>
                <vxe-column align="center" :edit-render="{ autofocus: '.vxe-input--inner' }" v-for="(itm, idx) in columnList" :key="idx">
                  <template #header>
                    <div class="solid-bottom" :class="itm.curDay ? 'text-orange text-bold' : 'text-black'">{{ itm.week }}</div>
                    <div :class="itm.curDay ? 'text-orange text-bold' : 'text-black'">{{ itm.title }}</div>
                  </template>
                  <template #default="{ row }">
                    <span v-if="row[itm.field]">
                      <span class="padding-lr-xs" v-for="(op, ii) in row[itm.field]" :key="ii" :style="getSpanBgColor(op)"> {{ op.scheValue }}</span>
                    </span>
                    <span v-else></span>
                  </template>
                  <template #edit="{ row, columnIndex }">
                    <SelectDataCheckedList
                      v-if="row && row.employeeId"
                      :url="'/api/scheduletype/findSchduleTypePage'"
                      ref="ruleSelectListRef"
                      :column="[
                        { field: 'symbol', title: '符号' }, //列标题
                        { field: 'name', title: '名称' },
                        { field: 'remark', title: '备注' }
                      ]"
                      :searchParam="{}"
                      :isPage="false"
                      :showField="symbol"
                      @SelectCellClick="
                        (e) => {
                          checkBox(row, columnIndex, e);
                        }
                      "
                      :clickRowId="getColumnScheTypes(row[itm.field])"
                    ></SelectDataCheckedList>
                  </template> </vxe-column
              ></vxe-colgroup>
            </vxe-table>
          </div>
        </Pane>
      </Splitpanes>
    </div>
  </div>
</template>

<script setup lang="ts">
// 引入组件区 =========
import { ref, reactive, getCurrentInstance, onMounted } from 'vue';
import Breadcrumb from '@/components/Breadcrumb.vue';
import { Splitpanes, Pane } from 'splitpanes';
import { formatDateTime } from '@/utils/common';
import SelectDataCheckedList from '@/components/SelectMultDataGrid.vue';
import { VxeMessage, VxeNotifyType } from '@/utils/CommonMessage'; //提示信息
import { VXETable } from 'vxe-table';

// 变量定义区 ==========
let { proxy }: any = getCurrentInstance();
let showLoading = ref(false); //刷新
const scheTypeList = reactive([]);
let tableDataList = reactive([]);
let columnList = reactive([]);
let employeeList = reactive([]);
let form = reactive({
  date: formatDateTime(new Date(), 'yyyy-MM')
});
let monthDataEmployeeMap = reactive({
  [form.date]: []
});

// 方法定义区
onMounted(() => {
  getScheTypeList();
  getEmployeeList();
});

// 获取排班类型列表
function getScheTypeList() {
  showLoading.value = true;
  const url = '/api/scheduletype/findSchduleTypePage';
  proxy.$http.get(url, { params: {} }).then((res: any) => {
    scheTypeList.push(...res.data);
    showLoading.value = false;
  });
}

// 获取单元格回显排班方式
function getColumnScheTypes(columnData: any) {
  if (columnData) {
    return columnData.map((item) => item.scheTypeId).join(',');
  } else {
    return '';
  }
}

// 获取人员列表
function getEmployeeList() {
  employeeList.length = 0;
  const url = '/wk/employee/getEmployeeList';
  proxy.$http
    .get(url)
    .then((res: any) => {
      employeeList.push(...res.data);
      getColumnList();
    })
    .catch((err: any) => {
      proxy.$alert(err, '提示');
    });
}

// 获取人员信息
function formatterEmployee(cellValue) {
  const employee = employeeList.find((item) => item.id === cellValue);
  return employee ? employee.name : '';
}

// 获取 表格列 和 表格数据
function getColumnList() {
  columnList.length = 0;
  tableDataList.length = 0;
  monthDataEmployeeMap[form.date] = [];
  const param = form.date + '-01';
  const url = '/wk/scheRecs/getColumnData/' + param;
  proxy.$http
    .get(url)
    .then((res: any) => {
      columnList.push(...res.data.columnList);
      tableDataList.push(...res.data.dataList);
      monthDataEmployeeMap[form.date].push(...employeeList.filter((item) => !tableDataList.map((item) => item.employeeId).includes(item.id)));
    })
    .catch((err: any) => {
      proxy.$alert(err, '提示');
    });
}
// 添加方法
function handleAdd() {
  const newRow = {
    id: null,
    code: '',
    name: '',
    inputCode: '', //输入码
    standardName: '' //标准名称
  };
  tableDataList.push(newRow);
  const $table = proxy.$refs.jobSchedulingTable as any;
  $table.reloadData(tableDataList);
  $table.setEditRow(newRow);
  $table.setCurrentRow(newRow);
}
// 单元格下拉确认
function checkBox(row: any, columnIndex: any, event: any) {
  const scheObjects = [];
  if (event.length > 0) {
    event.forEach((element) => {
      let scheObject = {
        employeeId: row.employeeId,
        year: columnList[columnIndex].year,
        month: columnList[columnIndex].month,
        day: columnList[columnIndex].day,
        week: columnList[columnIndex].week,
        recDate: columnList[columnIndex].datestr,
        scheTypeId: element ? element.id : '',
        scheValue: element ? element.symbol : '',
        texColor: element ? element.wordColor : '',
        bgColor: element ? element.bgColor : ''
      };
      scheObjects.push(scheObject);
    });
  } else {
    proxy.$http
      .delete('/wk/scheRecs/deleteScheRecsByDate', { params: { employeeId: row.employeeId, recDate: columnList[columnIndex].datestr } })
      .then((res: any) => {
        if (res.status.code == 1) {
          VxeMessage('删除成功', VxeNotifyType.success);
          getColumnList();
        } else {
          VxeMessage('删除失败', VxeNotifyType.error);
        }
      })
      .catch((err: any) => {
        proxy.$alert(err, '提示');
      });
    return;
  }

  const url = '/wk/scheRecs/saveBatchSche';
  proxy.$http
    .post(url, scheObjects)
    .then((res: any) => {
      if (res.status.code == 1) {
        VxeMessage('保存成功', VxeNotifyType.success);
        getColumnList();
      } else {
        VxeMessage('保存失败', VxeNotifyType.error);
      }
    })
    .catch((err: any) => {
      proxy.$alert(err, '提示');
    });
}
// 背景颜色控制
function getSpanBgColor(op) {
  let colorStr = { backgroundColor: '#fff', color: '#000' };
  if (op) {
    colorStr = { backgroundColor: op.bgColor, color: op.texColor };
  }
  return colorStr;
}

// 删除
function handleDelete() {
  const $xTable = proxy.$refs.jobSchedulingTable as any;
  const selectRows = $xTable.getCheckboxRecords();
  if (selectRows.length <= 0) {
    VxeMessage('请先选中要删除的项', VxeNotifyType.warning);
    return;
  }
  proxy
    .$confirm('确定删除此项？', '提示', {
      cancelButtonClass: 'cancel-button',
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    .then((type) => {
      if (type === 'confirm') {
        selectRows.forEach((item, idx) => {
          const url = '/wk/scheRecs/deleteByEmployeeId';
          proxy.$http
            .delete(url, { params: { employeeId: item.employeeId, recDate: form.date + '-01' } })
            .then((res: any) => {
              if (idx === selectRows.length - 1) {
                VxeMessage('删除成功', VxeNotifyType.success);
                getColumnList();
              }
            })
            .catch((err) => {
              VxeMessage(err, VxeNotifyType.error);
            });
        });
      }
    });
}

// 检验科快速排班
function expendEmployee() {
  proxy
    .$confirm('快速排班会清除当月所有排班数据，重新添加人员信息，是否继续？', '提示', {
      cancelButtonClass: 'cancel-button',
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    .then((type) => {
      if (type === 'confirm') {
        proxy.$http
          .get('/wk/scheRecs/lisDeptDataImport', { params: { recDate: form.date + '-01' } })
          .then((res: any) => {
            if (res.status.code == 1) {
              VxeMessage('排班成功', VxeNotifyType.success);
              getColumnList();
            } else {
              VxeMessage('排班失败', VxeNotifyType.error);
            }
          })
          .catch((err: any) => {
            proxy.$alert(err, '提示');
          });
      }
    });
}
// 下月快速排班
function createNextMonthScheRec() {
  proxy
    .$confirm('下月快速排班会先清空下月数据，是否继续？', '提示', {
      cancelButtonClass: 'cancel-button',
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    .then((type) => {
      if (type === 'confirm') {
        proxy.$http
          .get('/wk/scheRecs/quicklyNextMonthScheRecs', { params: { currentMonth: form.date + '-01' } })
          .then((res: any) => {
            if (res.status.code == 1) {
              VxeMessage(res.status.msg, VxeNotifyType.success);
            } else {
              VxeMessage(res.status.msg, VxeNotifyType.error);
            }
          })
          .catch((err: any) => {
            proxy.$alert(err, '请求异常');
          });
      }
    });
}

// 导入excel
function importExcelData() {
  proxy
    .$confirm('下月快速排班会先清空当月数据，是否继续？', '提示', {
      cancelButtonClass: 'cancel-button',
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    .then(async (type) => {
      if (type === 'confirm') {
        const { file } = await VXETable.readFile({ types: ['xlsx', 'xls'] });
        let formData = new FormData();
        formData.append('name', 'myk');
        formData.append('file', file);
        proxy.$http
          .post('/wk/scheRecs/importExcelData', formData)
          .then((res: any) => {
            if (res.status.code == 1) {
              VxeMessage(res.status.msg, VxeNotifyType.success);
              getColumnList();
            } else {
              VxeMessage(res.status.msg, VxeNotifyType.error);
            }
          })
          .catch((err: any) => {
            proxy.$alert(err, '请求异常');
          });
      }
    });
}
</script>

<style lang="scss" scoped>
#jobScheduling {
  height: 100%;
  .bodyContent {
    height: calc(100% - 60px);
    .area {
      background-color: $base-white;
      // 附加按钮间距
      .button-blue,
      .button-red {
        margin: 5px 0 5px 5px;
      }
      .wkEmployeeBox {
        height: calc(100% - 40px);
      }
      .el-tabs {
        height: 100%;
      }
      .jobSchedulingTable {
        height: 100%;
      }
      :deep(.el-tabs__content) {
        height: calc(100% - 39px);
        padding: 0;
        .el-tab-pane {
          height: 100%;
        }
        #pane-0 {
          padding: 15px;
          height: calc(100% - 30px);
          .el-form {
            height: 100%;
          }
        }
      }
    }
  }
}
</style>
